<?php

namespace App\Http\Middleware;

use App\Models\Log;
use App\Models\Permission;
use Closure;
use Auth;
use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Facades\DB;

class BeforeMiddleware
{
    use Helpers;
    //前置中间件
    public function handle($request, Closure $next)
    {
        $name = $request->route()->getName();
        //IP白名单
        $ips = DB::table('ips')->pluck('ip')->toArray();
        if(env('IP_ENABLED')){
            if(!in_array($request->getClientIp(), $ips)){
                return response()->json(['error' => '未加入IP白名单'], 422);
            }
        }

        //登陆退出的日志记录
        if($name == 'api.auth.logout'){
            Log::create([
                'user_id' => Auth::user()->id,
                'ip' => empty(Auth::user()->login_ip)?'':Auth::user()->login_ip,
                'content' =>  '登出操作'
            ]);
        }
        return $next($request);
    }
}
